package com.itheima.reggie.filter;

import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.utils.BaseContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        
        //1. 获取请求地址
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        

        String requestPath = req.getRequestURI() ;
        
        //2. 判断请求地址是否属于直接放行的地址
        if(requestPath.contains("login") || requestPath.contains("logout")
                ||requestPath.endsWith(".js") ||requestPath.endsWith(".css") || requestPath.contains("images")
                || requestPath.contains("element") || requestPath.contains("ico") || requestPath.contains("smscode")
                || requestPath.endsWith("doc.html") || requestPath.contains("webjars") || requestPath.contains("swagger-resources")
                || requestPath.contains("api-docs")){
            //直接放行！
            filterChain.doFilter(servletRequest, servletResponse);
         
            return ;
        }
        
        //3. 如果不属于以上直接放行的路径，那么就要判断是否有登录。
        Employee employee = (Employee) req.getSession().getAttribute("employee");
        
        //3.1 判断是否有值
        if(employee != null){//已经登录过

            BaseContext.set(employee.getId());

            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return ;
        }

        //4. 加上前端用户的登录判断
        User user = (User) req.getSession().getAttribute("user");
        if(user != null ){

            BaseContext.set(user.getId());

            filterChain.doFilter(servletRequest, servletResponse);
            return ;
        }

        //处理客户端页面的跳转登录
        if (requestPath.contains("backend")) {
            resp.sendRedirect("/backend/page/login/login.html");
        } else {
            resp.sendRedirect("/front/page/login.html");
        }

    }
}
